import path from 'path';

import {expect} from '@jest/globals';
import fse from 'fs-extra';

import { getJson5Obj } from '../../../../src/utils/json-util.js';
import { runHvigorAsync, setDefaultStrictMode } from '../../common/common';
import {WorkerDataEts, WorkerDataTs} from '../../plugins/common-data';
import {
  AbilityType,
  APIType,
  CaseLevel, CURRENT_HMOS_API,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { Project } from '../../plugins/project-builder/models/project-models';
import { ICaseRecord } from '../../plugins/report-builder/report-models';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';


const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: CURRENT_HMOS_API,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  }
};
/**
 *  1. hvigor-config设置sourceMap生成路径
 *  2. 构建hap包
 *  3. 构建之后检查sourceMaps.map是否存在于指定路径
 *  4. 增加worker，增量构建sourceMap.map，应该存在worker信息
 */
const testFun: TestCaseFun = async (project: Project, taskConfig: TestTaskOption, record: ICaseRecord) => {

  const projectRoot = project.projectRootPath();
  setDefaultStrictMode(projectRoot);
  // 指定生成sourceMap的父文件夹
  const outputSourceMapPath = path.resolve(projectRoot, 'test111');

  const rootPath = project.projectRootPath();
  const hvigorConfigPath = path.resolve(rootPath, 'hvigor', 'hvigor-config.json5');
  const hvigorConfigObj = getJson5Obj(hvigorConfigPath);

  // hvigor-config增加配置，添加sourceMap的路径
  hvigorConfigObj.properties = {
    'ohos.arkCompile.sourceMapDir': outputSourceMapPath,
  };
  fse.writeFileSync(hvigorConfigPath, JSON.stringify(hvigorConfigObj));

  // 构建hap包,成功在指定路径生成sourceMap
  const commandHap = ['assembleHap'];
  await runHvigorAsync(project.projectRootPath(), commandHap);
  const entryName = project.getModule('entry').name;
  const entryPath = project.getModule('entry').moduleRootPath();
  expect(fse.existsSync(path.resolve(outputSourceMapPath, entryName, 'sourceMaps.map'))).toBe(true);

  // 增加一个worker.ets, 看增量场景下sourceMap是否还存在问题
  const workerData = project.option.apiType === APIType.STAGE ? WorkerDataEts : WorkerDataTs;
  const extendStr = project.option.apiType === APIType.STAGE ? 'ets' : 'ts';
  await fse.ensureDir(path.resolve(entryPath, 'src/main/ets/workers'));
  await fse.writeFile(path.resolve(entryPath, `src/main/ets/workers/Worker.${extendStr}`), workerData);
  // 增量编译
  await runHvigorAsync(project.projectRootPath(), commandHap);
  expect(fse.existsSync(path.resolve(outputSourceMapPath, entryName, 'sourceMaps.map'))).toBe(true);

  // 检查sourceMap是否存在worker字段
  const hapSourceMapStr = fse.readFileSync(path.resolve(outputSourceMapPath, entryName, 'sourceMaps.map')).toString();
  expect(hapSourceMapStr.includes(`Worker.${extendStr}`)).toBe(true);

};

TestCaseBuilder.builder()
  .caseName('sourceMap_Info_Lost_in_Incremental_task')
  .description('增量场景下sourceMap信息缺失')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testFun)
  .load();
